#include <list.h>
#include <stdatomic.h>

struct condition {
	atomic_flag flag;
	// 用于记录在当前条件变量上等待的线程数量
	int num_waiting;
	// 用于存放等待当前条件的线程的队列
	struct list_head wait_list;	
};

void wait(struct condition *con, pthread_mutex_t lock) {
	while (atomic_flag_test_and_set(&sem->flag));
	
	con->num_waiting++;
	
	list_add_tail(&sem->wait_list, current_thread);
	
	atomic_flag_clear(&sem->flag);
	
	// 至于这里为什么这么做，我们在后面会讲
	pthread_mutex_unlock(&lock)
	park();
	pthread_mutex_lock(&lock)
}

void signal(struct condition *con, pthread_mutex_t lock) {
    while (atomic_flag_test_and_set(&sem->flag));
	
	if (con->num_waiting > 0) {
   		wait_thread = list_first_entry(&sem->wait_list);
		list_del_first(&sem->wait_list);
	
		unpark(wait_thread);
	
		con->num_waiting--;
	}
   	atomic_flag_clear(&sem->flag);
}

